package com.liang.controller;

import com.liang.dao.DepartmentDao;
import com.liang.dao.EmployeeDao;
import com.liang.pojo.Department;
import com.liang.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;


@Controller
public class EmployeeController {
    @Autowired
    EmployeeDao employeeDao;
    @Autowired
    DepartmentDao departmentDao;

    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.getEmployees();
        model.addAttribute("emps",employees);
        return "emp/list";
    }

    //跳转至添加员工页面
    @GetMapping("/toAdd")
    public String toAdd(Model model){
        //获取所有部门信息（下拉列表中需要）
        Collection<Department> departments = departmentDao.getAllDepartments();
        model.addAttribute("departments",departments);
        return "emp/add";
    }

    //添加员工
    @PostMapping("/add")
    public String add(Employee employee){
        System.out.println("employee==>"+employee);
        //添加员工
        employeeDao.add(employee);
        return "redirect:/emps";
    }

    //跳转至修改页面
    @GetMapping("/toUpdate/{id}")
    public String toUpdate(@PathVariable Integer id,Model model){
        //查出员工信息
        Employee employee = employeeDao.getEmployeeById(id);
        model.addAttribute("employee",employee);
        //查出所有部门信息
        Collection<Department> departments = departmentDao.getAllDepartments();
        model.addAttribute("departments",departments);
        return "emp/update";
    }

    //修改员工信息
    @PostMapping("/update")
    public String update(Employee employee){
        employeeDao.add(employee);
        return "redirect:/emps";
    }

    //删除员工
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable Integer id){
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}
